<template>
  <div class="container">
    <el-card>
      <div class="set-container">
        <div class="select-container">
          <el-form ref="selectForm" :inline="true" :model="selectForm" class="select-form">
            <el-form-item prop="name" label="商品名:">
              <el-input v-model="selectForm.name" placeholder="请输入商品名" class="select-input-1" size="medium"></el-input>
            </el-form-item>
            <el-form-item prop="date" label="创建时间:">
              <el-date-picker
                  size="medium"
                  v-model="selectForm.date"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item prop="status" label="商品状态">
              <el-select class="select-input-2" v-model="selectForm.status" placeholder="请选择" size="medium">
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="category" label="选择分类">
              <el-select v-model="selectForm.category" placeholder="请选择" size="medium">
                <el-option
                    v-for="item in category"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button-group>
                <el-button type="primary" size="medium" @click="submitSelect(1)">查询</el-button>
                <el-button type="info" size="medium" @click="resetSelect">重置</el-button>
              </el-button-group>
            </el-form-item>
          </el-form>
        </div>
        <div class="button-container">
          <el-button type="success" size="medium" @click="addMer">新增商品</el-button>
          <el-button type="danger" size="medium" @click="showDialog">批量操作</el-button>
          <el-button type="info" size="medium">导出表格</el-button>
        </div>
      </div>
      <el-divider><h3 style="text-align: center">商品信息表格</h3></el-divider>
      <div class="table-container">
        <el-table
            v-if="tableData.length > 0"
            :data="tableData"
            @selection-change="handleSelectionChange"
            border
            stripe
            style="width: 100%">
          <el-table-column
              type="selection"
              width="45">
          </el-table-column>
          <el-table-column
              prop="name"
              label="商品名"
              width="140">
          </el-table-column>
          <el-table-column
              prop="volume"
              label="商品体积"
              width="90">
          </el-table-column>
          <el-table-column
              prop="weight"
              label="商品重量"
              width="90">
          </el-table-column>
          <el-table-column
              prop="stock"
              label="商品库存"
              width="90">
          </el-table-column>
          <el-table-column
            prop="price"
            label="商品价格"
            width="110">
            </el-table-column>
          <el-table-column
              prop="categoryName"
              label="所属分类"
              width="120">
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="200">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              {{ formatCreateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column
              prop="createUser"
              label="创建者"
              width="120">
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" effect="dark">启用</el-tag>
              <el-tag v-else-if="scope.row.status === 0" type="warning" effect="dark">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="260">
            <template slot-scope="scope">
              <el-button-group>
                <el-button type="primary" icon="el-icon-edit" size="mini" plain @click="openEditUserDialog(scope.row.id)" >编辑</el-button>
                <el-button type="success" size="mini" plain >详情</el-button>
                <el-button  v-if="scope.row.status===1" type="warning" icon="el-icon-lock" size="mini" plain @click="logout(scope.row.id,0)" >停用</el-button>
                <el-button  v-else icon="el-icon-unlock" size="mini" plain @click="logout(scope.row.id,1)">启用</el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        <el-empty :image-size=350  v-else description="暂无数据"></el-empty>
      </div>
      <el-divider></el-divider>
      <div class="page">
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="selectForm.page"
            :page-sizes="[5, 7, 10, 20, 50]"
            :page-size="selectForm.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
        title="新增商品"
        :visible.sync="merDialogVisible"
        width="70%"
        top="3vh">
      <el-form
          :model="addMerForm"
          :rules="addMerRules"
          ref="addMerForm"
          label-width="100px"
          class="addMerForm"
      >
       <div class="form-mer">
        <div class="input">
        <el-form-item prop="name" label="商品名">
          <el-input
              v-model="addMerForm.name"
              maxlength="16"
              show-word-limit
          ></el-input>
        </el-form-item>
          <el-form-item prop="brief" label="商品简要描述">
            <el-input
                v-model="addMerForm.brief"
                maxlength="20"
                show-word-limit
                type="textarea"
            ></el-input>
          </el-form-item>
          <el-form-item prop="description" label="商品详细描述">
            <el-input
                v-model="addMerForm.description"
                maxlength="255"
                show-word-limit
                type="textarea"
            ></el-input>
          </el-form-item>
          <el-form-item prop="volume" label="体积(dm)">
            <el-input
                type="number"
              v-model="addMerForm.volume"
              ></el-input>
          </el-form-item>
          <el-form-item prop="weight" label="重量(kg)">
            <el-input
                type="number"
                v-model="addMerForm.weight"
            ></el-input>
          </el-form-item>
          <el-form-item prop="stock" label="库存">
            <el-input
              type="number"
              v-model="addMerForm.stock"
              ></el-input>
            </el-form-item>
          <el-form-item prop="price" label="价格(￥)">
            <el-input
                v-model="addMerForm.price"
            ></el-input>
          </el-form-item>
          <el-form-item prop="category" label="所属分类">
            <el-select v-model="addMerForm.categoryId" placeholder="请选择" size="medium">
              <el-option
                  v-for="item in category"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="detail" label="详细描述">

          </el-form-item>
        </div>

        <div class="addMerForm-item-image">
          <el-form-item prop="image" label="商品主图片">
            <ImgCutter
                rate="1:1"
                :sizeChange="false"
                v-on:cutDown="cutDown"
            ></ImgCutter>
            <el-image
                v-if="addMerForm.image" :src="addMerForm.image" class="avatar" alt=""
                :preview-src-list="srcList">
            </el-image>
            <i v-else class="el-icon-picture-outline avatar-uploader-icon"></i>

          </el-form-item>
          <el-form-item prop="imageSecond" label="商品副图片">
            <el-upload
                class="upload-demo"
                action=""
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-upload="beforeUpload"
                multiple
                :limit="3"
                :on-exceed="handleExceed"
                :file-list="fileList"
                list-type="picture"
                :http-request="uploadSecond">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1mb</div>
            </el-upload>
          </el-form-item>
        </div>
       </div>
      </el-form>
    </el-dialog>

  </div>
</template>
<script>
import axios from "@/api/axios";
import ImgCutter from 'vue-img-cutter'

export default {
  components:{
    ImgCutter
  },

  data() {
    return {
      selectForm:{
        name:"",
        date:"",
        pageSize:7,
        page:1,
        status:"",
        category:""
      },
      total:0,
      tableData: [], // 表格数据

      merDialogVisible: false,
      addMerForm: {
        name: "",
        brief:"",
        description:"",
        volume:"",
        weight:"",
        stock:"",
        price:"",
        categoryId:"",
        detail:"",
        image:"",
        imageList:[],
      },
      fileList: [],
      srcList:[],

      options: [
        {
          value: 0,
          label: '停用'
        }, {
          value: 1,
          label: '启用'
        }
      ],

      category: [],
    }
  },

  mounted() {
    this.queryCategory();
    this.submitSelect();
  },

  methods:{
    /**
     * 表格数据查询函数
     */
    submitSelect(flag) {
      this.$refs.selectForm.validate((valid) => {
        if (flag===1) {
          this.selectForm.page = 1;// 重新查询时，将页码置为第一页
        }
        if (valid) {
          const formData = {
            page: this.selectForm.page,
            pageSize: this.selectForm.pageSize,
            name: this.selectForm.name,
            begin: this.formatDate(this.selectForm.date[0]),
            end: this.formatDate(this.selectForm.date[1]),
            status: this.selectForm.status,
            categoryId: this.selectForm.category
          };

          axios.post("/admin/merchandise/page", formData).then(response => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            }else {
              this.tableData = response.data.data.records;
              this.total = response.data.data.total;
            }
          }).catch(error=> {
            // 处理请求错误
            console.log(error);
          });
        }else{
          console.log("error submit!");
          return false;
        }
      })
    },

    /**
     * 日期处理函数
     * @param date
     * @returns {null|string}
     */
    formatDate(date) {
      if (date instanceof Date) {
        // 返回格式化后的日期时间字符串（ISO 8601 UTC格式，不包含毫秒）
        return (
            date.toISOString().split("T")[0] +
            "T" +
            date.toISOString().split("T")[1].split(".")[0]
        );
      } else {
        // 如果日期为空或者不是Date对象，返回null或空字符串，或者根据你的需求返回其他默认值
        return null; // 或者 ""，取决于后端如何处理这种情况
      }
    },

    /**
     * 查询分类
     */
    queryCategory(){
      axios.get("/admin/category/query").then((response) => {
        if(response.data.code===0){
          this.$message.error(response.data.msg);
        }else {
          this.category = response.data.data;
        }
      }).catch((error) => {
        console.log(error);
      });
    },

    /**
     * 查询表单重置函数
     */
    resetSelect() {
      this.$refs.selectForm.resetFields(this.selectForm);
      this.$message.info("重置成功");
    },

    /**
     * 两个分页选项函数
     * @param val
     */
    handleSizeChange(val) {
      this.selectForm.pageSize = val;
      this.submitSelect();
    },
    handleCurrentChange(val) {
      this.selectForm.page=val;
      this.submitSelect();
    },

    /**
     * 给返回的时间格式化函数
     * @param {Array} createTime - 包含年、月、日、时、分、秒的数组
     * @returns {string}
     */
    formatCreateTime(createTime) {
      const [year, month, day, hour, minute = '00', second = '00'] = createTime;
      return `${year}-${this.padZero(month)}-${this.padZero(day)} ${this.padZero(hour)}:${this.padZero(minute)}:${this.padZero(second)}`;
    },

    /**
     * 将数字补零
     * @param {number|string} num
     * @returns {string}
     */
    padZero(num) {
      return num.toString().padStart(2, '0');
    },

    /**
     * 打开新增商品
     */
    addMer(){
      this.merDialogVisible = true;
    },

    /**
     * 图片上传
     */
    cutDown(res){
      if(this.beforeUpload(res.file)){
        this.upload(res);
      }else{
        return false;
      }
    },

    beforeUpload(file) {
      // 检查文件是否为JPG或PNG格式
      const isValidFormat = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 1; // 检查文件大小是否小于1MB

      if (!isValidFormat) {
        this.$message.error("上传图片只能是 JPG 或 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 1MB!");
      }
      // 只有当文件是JPG或PNG格式且大小不超过1MB时，才返回true
      return isValidFormat && isLt2M;
    },

    /*图片上传方法*/
    upload(file) {
      axios.post("/admin/common/upload", file,{headers:{'Content-Type': 'multipart/form-data',}}).then((response) => {
        if(response.data.code===0){
          this.$message.error(response.data.msg);
        }else {
          this.addMerForm.image=response.data.data;
          this.srcList.push(response.data.data);
          this.$message.success("上传成功");
        }
      }).catch((error) => {
        console.log(error);
      })
    },

    /**
     * 副图片上传
     */
    handleRemove(file, fileList) {
      console.log(file, fileList);
      const index = this.fileList.indexOf(file); // 查找要移除的文件在fileList中的索引
      if (index !== -1) { // 如果文件存在于fileList中
        this.fileList.splice(index, 1); // 使用splice方法从fileList中移除该文件
      }
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },

    uploadSecond(file){
      axios.post("/admin/common/upload", file,{headers:{'Content-Type': 'multipart/form-data',}}).then((response) => {
        if(response.data.code===0){
          this.$message.error(response.data.msg);
        }else {
          this.addMerForm.imageList.push(response.data.data);
          this.$message.success("上传成功");
        }
      }).catch((error) => {
        console.log(error);
      })
    },
  }
}
</script>

<style>
/*收缩选择框所占空间*/
.select-input-1{
  width: 100px;
}

.select-input-2{
  width: 120px;
}

/*表格最小高度*/
.table-container{
  min-height: 60vh;
}

/*表格顶部设置栏*/


/*分页*/
.page{
  margin-top: 20px;
}

/*图片上传样式*/
.avatar-uploader-icon {
  margin-top: 10px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  margin-top: 10px;
  width: 150px;
  height: 150px;
  display: block;
}

/*新增表单样式*/
.form-mer, .addMerForm-item-image{
  display: flex;
}

.input{
  width: 35%;
}

</style>